/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hazardsource.controller;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.hazardsource.domain.CheckListEntry;
import com.koron.hazardsource.service.api.CheckListService;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "checkList",description = "标准检查表接口类")
@RestController
@RequestMapping("/checkList")
public class CheckListController {

	@Autowired
	private CheckListService checkListService;

	@ApiOperation("保存草稿")
	@RequestMapping(value = "/saveCheckListDraft.htm", method = { RequestMethod.POST })
	@Log(title = "标准检查表保存草稿", businessModule = "标准检查表", businessManipulation = BusinessManipulation.INSERT)
	public MessageBean<?> saveCheckListDraft(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
			@RequestBody List<CheckListEntry> beanList){
		if(user==null){
			MessageBean<?>msg=new MessageBean<>();
			msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
			return msg;
		}
		MessageBean<?> msg = checkListService.saveCheckListDraft(beanList,user);
		return msg;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiImplicitParams({
        @ApiImplicitParam(name = "name", value = "检查表名称", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "businessTypeId", value = "业态类型", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "checklistEntryTypeId", value = "检查表类型", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")})
	@ApiOperation("标准检查表列表")
	@RequestMapping(value = "/list.htm", method = { RequestMethod.GET })
	public MessageBean<?> list(String businessTypeId, String name, String checklistEntryTypeId,Integer page,
			Integer pageSize){
		MessageBean<DataBean> msg=new MessageBean<>();
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
		List<CheckListEntry> list = checkListService.list("checklist_entry", businessTypeId, name, checklistEntryTypeId, start, end);
		totalNumber = checkListService.count("checklist_entry", businessTypeId, name, checklistEntryTypeId);
		if(start != null && end != null){
			totalPage = (totalNumber+pageSize-1)/pageSize;
		}else{
			totalPage = 1;
			page = totalPage;
			pageSize = totalNumber;
		}

		DataBean data = new DataBean();
		data.setList(list);
		data.setPageNo(page);
		data.setPageSize(pageSize);
		data.setTotalNumber(totalNumber);
		data.setTotalPage(totalPage);
		msg.setData(data);
		return msg;
	}

	@ApiOperation("提交操作")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "title", value = "标题", paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "note", value = "说明", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/submitCheckEntryItem.htm", method = { RequestMethod.POST })
    @Log(title = "新增、修改检查表提交操作", businessModule = "标准检查表", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> submitCheckEntryItem(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody List<CheckListEntry> beanList,String title,String note){
		if(user==null){
			MessageBean<?>msg=new MessageBean<>();
			msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
			return msg;
		}
		MessageBean<?> msg=checkListService.submitCheckEntryItem(beanList,user,title,note);
        return msg;
    }

	@ApiOperation("废弃检查表")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "title", value = "标题", paramType = "query", dataType = "String"),
    	@ApiImplicitParam(name = "note", value = "说明", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/discard.htm", method = { RequestMethod.POST })
    @Log(title = "废弃检查表", businessModule = "标准检查表", businessManipulation = BusinessManipulation.UPDATE)
	public MessageBean<?> discard(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam(value = "idList") List<String> idList,String title, String note){
		if(user==null){
			MessageBean<?>msg=new MessageBean<>();
			msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
			return msg;
		}
        MessageBean<?> msg= checkListService.discard(idList, user,title, note);
        return msg;
    }

	@ApiOperation("删除草稿")
	@ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "String")
    @RequestMapping(value = "/deleteDraft.htm", method = { RequestMethod.GET })
	public MessageBean<?> deleteDraft(String id){
		return checkListService.deleteDraft(id);
	}

	@ApiOperation("获取检查表详情")
	@ApiImplicitParam(name = "id", value = "检查表id", paramType = "query", dataType = "String")
    @RequestMapping(value = "/details.htm", method = { RequestMethod.GET })
	public MessageBean<?> details(String id){
		MessageBean<CheckListEntry> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, CheckListEntry.class);
		CheckListEntry bean = checkListService.details("checklist_entry","checklist_item",id);
		msg.setData(bean);
        return msg;
	}

	@ApiOperation("根据获code取检查表详情")
	@ApiImplicitParam(name = "code", value = "检查表code", paramType = "query", dataType = "String")
    @RequestMapping(value = "/detailsByCode.htm", method = { RequestMethod.GET })
	public MessageBean<?> detailsByCode(String code){
        return checkListService.detailsByCode(code);
	}

	@ApiOperation(value = "导入检查表和检查项")
	@ApiImplicitParams({
		    @ApiImplicitParam(name = "checkCode", value = "检查表编号", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "checklistEntryTypeId", value = "检查表类型", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "businessTypeId", value = "业态id", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "title", value = "标题", required = true, paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "note", value = "备注", required = true, paramType = "query", dataType = "String") })
	@RequestMapping(value = "/importExcel.do", method = { RequestMethod.POST })
	public MessageBean<?> improtExcel(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,MultipartFile uploadFile,String checkCode,String checklistEntryTypeId,
			String businessTypeId,String title,String note) {
		if(user==null){
			MessageBean<?>msg=new MessageBean<>();
			msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
			return msg;
		}
		return checkListService.importExcel(user, checkCode, checklistEntryTypeId, businessTypeId, title, note,uploadFile);
	}
	@ApiOperation("导出检查表")
	@ApiImplicitParam(name = "id", value = "检查表id", required = true, paramType = "query", dataType = "String")
	@RequestMapping(value = "/exportsHazardSource.htm" , method = { RequestMethod.GET })
	public HttpEntity<?> exports(String id){
		CheckListEntry clb = checkListService.details("checklist_entry", "checklist_item", id);
	 	Map<String, Object> map = new HashMap<>();
		map.put("data", clb);
		File targetFile = new File("static/excel/stdCheckEntry.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/stdCheckEntry.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
        	return null;
        }
		return Excel.createFile(clb.getName(),targetFile, "stdCheckEntry.btl",map);
	}

	@ApiOperation("标准检查表草稿列表")
    @RequestMapping(value = "/getDraftList.htm", method = { RequestMethod.GET })
    public MessageBean<?> getDraftList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user){
		if(user==null){
			MessageBean<?>msg=new MessageBean<>();
			msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
			return msg;
		}
    	return checkListService.getDraftList(user);
    }
	@ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(String ids){
    	return checkListService.getProcessData(ids);
    }

	@ApiOperation("历史版本")
    @ApiImplicitParam(name = "code", value = "标准检查表code", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getHistoryList.htm", method = {RequestMethod.GET})
    public MessageBean<?> getHistoryList(String code){
    	return checkListService.getHistoryList(code);
    }
	@ApiOperation(value = "下载检查表excel模板")
    @RequestMapping(value = "/downloadtemplate.htm", method = {RequestMethod.GET})
    public HttpEntity<?> downloadTemplate() {
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/stdCheckEntryTemplate.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/stdCheckEntryTemplate.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            return null;
        }
        return Excel.createFile("标准检查表模板", targetFile, "default.btl", map);
    }

}
